package com.opennews.openplatform

import groovy.transform.CompileStatic
import org.springframework.http.HttpStatus

@CompileStatic
class UserController extends BaseController {
    static allowedMethods = [
        updateCurrentUserPassword: "POST",
        updateCurrentUser: "POST",
        updateRoles: "POST"
    ]

    UserService userService

    // region: Get actions.
    def index() {
        render("UserController")
    }

    def queryDetails() {
        def id = params.id.toString()
        def accountGroupId = getClaims().accountGroupId
        def result = userService.queryDetails(accountGroupId, id)

        sendDataResponse(result)
    }

    def queryUsersNotInAccountGroup() {
        def keyword = params.keyword.toString()
        def pageSize = params.int("pageSize")
        def pageIndex = params.int("pageIndex")
        def accountGroupId = getClaims().accountGroupId
        def result = userService.queryUsersNotInAccountGroup(accountGroupId, keyword, pageSize, pageIndex)

        sendDataResponse(result)
    }

    def queryAccountGroupUsers() {
        def pageSize = params.int("pageSize")
        def pageIndex = params.int("pageIndex")
        def accountGroupId = getClaims().accountGroupId
        def result = userService.queryAccountGroupUsers(accountGroupId, pageSize, pageIndex)

        sendDataResponse(result)
    }
    // endregion

    // region: Post actions.
    def updateCurrentUserPassword() {
        def requestBodyData = getRequestBodyData()
        def claims = getClaims()

        // Checks if the current password is correct. Otherwise the password will not be updated.
        def isPasswordMatched = userService.validatePassword(claims.username, requestBodyData.currentPassword.toString())

        // If the current password matches then update to the new password.
        if (isPasswordMatched) {
            userService.updatePassword(claims.accountGroupId, claims.username, requestBodyData.newPassword.toString())
        }

        sendDataResponse(isPasswordMatched)
    }

    def updateCurrentUser() {
        def requestBodyData = getRequestBodyData()
        def claims = getClaims()
        def username = claims.username
        userService.updateCurrentUser(username, requestBodyData)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }

    def updateRoles() {
        def requestBodyData = getRequestBodyData()
        def accountGroupId = getClaims().accountGroupId
        userService.updateRoles(accountGroupId, requestBodyData)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }
    // endregion
}